package com.ctms.system.controller;

import com.ctms.common.utils.AESUtils;
import com.ctms.common.utils.MD5Utils;
import com.ctms.common.utils.R;
import com.ctms.common.utils.ShiroUtils;
import com.ctms.system.domain.UserDO;
import com.ctms.system.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@RequestMapping("/resetPwd")
@Controller
public class ResetPwdController {

    @Autowired
    UserService userService;

    @GetMapping("")
    public String reset(Model model){
        UserDO userDO = ShiroUtils.getUser();
        model.addAttribute("user",userDO);
        return "sys/user/reset_pwd";
    }

    @PostMapping("/reset")
    @ResponseBody
    R resetPassword(@Param("password") String password,@Param("oldPassword")String oldPassword){
        //获取当前登录用户信息
        UserDO user = ShiroUtils.getUser();
        String username = user.getUsername();
        //旧密码与用户加密，判断与数据库是否一致
        String oldPwd = MD5Utils.encrypt(username,oldPassword);
        //密码一致，执行修改操作
        if (oldPwd.equals(user.getPassword())){
            //加密
            user.setPassword(MD5Utils.encrypt(username, password));
            //更新密码操作
            if (userService.resetPwd(user) > 0) {
                //更新成功
                return R.ok();
            }else {
                //更新失败
                return R.error();
            }
        }else {
            //密码不一致，不修改
            return R.error(-1,"原始密码输入错误");
        }
    }

}
